package com.its.us.web.config.hasPermission;

import com.its.us.web.entity.sys.Menu;
import com.its.us.web.entity.sys.User;
import com.its.us.web.service.sys.MenuService;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 要想使用 hasPermission注解必须自定义实现
 *
 * @Author: master
 * @Date: 2020/10/30 12:21
 * @Version: 1.0
 */
@Component
public class MyPermissionEvaluator implements PermissionEvaluator {

    @Resource
    private MenuService menuService;

    /**
     * 主要两个方法 实现返回tre，默认返回false
     *
     * @return
     */

    public MyPermissionEvaluator() {
    }

    /**
     * 实现这里
     *
     * @param authentication
     * @param target
     * @param permission
     * @return
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object target, Object permission) {
        User user = (User) authentication.getPrincipal();
        try {
            List<Menu> currentMenus = menuService.getCurrentMenus(user.getUsername());
            List<Menu> menus = currentMenus.stream()
                    .filter(m -> !StringUtils.isEmpty(m.getMenuUrl()))
                    .filter(m -> !StringUtils.isEmpty(m.getPermission()))
                    .collect(Collectors.toList());
            if (menus.size() > 0) {
                return menus.stream().anyMatch(menu -> (menu.getMenuUrl().equals(target) && menu.getPermission().equals(permission)));
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}
